﻿namespace StockSharp.Connectors.Alfa
{
	using System.Diagnostics;

	using Ecng.Common;

	using StockSharp.Algo;
	using StockSharp.Algo.Strategies;
	using StockSharp.BusinessEntities;
	using StockSharp.Logging;

	class TestStrategy : Strategy
	{
		private int _mqsCouner;
		private OrderDirections _lastDirection;

		protected override void OnStarted()
		{
			this.AddInfoLog("Start test strategy");

			Trader.RegisterSecurity(Security);
			Trader.RegisterMarketDepth(Security);

			base.OnStarted();
		}

		public void StartMarketQuoting(OrderDirections direction, decimal offset)
		{
			var strategy = CreateMarketQuoting(direction, 1, offset);

			strategy.ProcessStateChanged += s =>
			{
				if (s.ProcessState == ProcessStates.Stopped)
				{
					this.AddInfoLog("Quoting stoped");
				}
			};

			strategy.Log += m => Trace.WriteLine(m.Time + ", " + m.Source + ", " + m.Message);

			this.ChildStrategies.Add(strategy);
		}

		public void StartLimitQuoting()
		{
			var price = Security.BestAsk.Price - Security.MinStepSize;
			var strategy = CreateLimitQuoting(OrderDirections.Sell, 1, price);

			strategy.ProcessStateChanged += s =>
			{
				if (s.ProcessState == ProcessStates.Stopped)
				{
					this.AddInfoLog("Quoting stoped");
				}
			};

			this.ChildStrategies.Add(strategy);
		}


		protected virtual QuotingStrategy CreateMarketQuoting(OrderDirections direction, decimal volume, decimal offset)
		{
			this.AddInfoLog("Create market quoting {0} {1}", direction, volume);

			return new MarketQuotingStrategy(direction, volume)
			{
				Name = "MQS {0}".Put(Security.Code),
				PriceOffset = Security.MinStepSize * offset
			};
		}

		protected virtual QuotingStrategy CreateLimitQuoting(OrderDirections direction, decimal volume, decimal price)
		{
			this.AddInfoLog("Create limit quoting {0} {1}", direction, volume);

			return new LimitQuotingStrategy(direction, volume, price)
			{
				Name = "LQS {0}".Put(Security.Code)
			};
		}

		public void StartMarketQuotingTest(decimal offset)
		{
			_mqsCouner = 0;

			StartMarketQuotingRecursive(OrderDirections.Buy, offset);
		}

		private void StartMarketQuotingRecursive(OrderDirections directions, decimal offset)
		{
			_lastDirection = directions;
			var strategy = CreateMarketQuoting(directions, 1, offset);

			strategy.ProcessStateChanged += s =>
			{
				if (s.ProcessState == ProcessStates.Stopped)
				{
					this.AddInfoLog("Quoting {0} stoped", _lastDirection);

					if (_mqsCouner++ < 5)
					{
						_lastDirection = _lastDirection == OrderDirections.Buy ? OrderDirections.Sell : OrderDirections.Buy;

						StartMarketQuotingRecursive(_lastDirection, offset);
					}
					else
					{
						this.AddWarningLog("MQS PASSED");
					}
				}
			};

			this.ChildStrategies.Add(strategy);			
		}
	}
}
